<template>
  <div ref="modal" class="modal">
    <a-modal :class="props.showType == 'ADD' ? 'addBox' : 'editBox'" centered :getContainer="() => $refs.modal" :visible="visible" :title="TITLE[showType]" @cancel="handleCancel">
      <div class="mb-4" v-if="props.showType == 'ADD'">
        <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
      </div>
      <a-tabs class="mb-4" v-model:activeKey="state.activeKey" v-else>
        <a-tab-pane key="1" tab="基本信息">
          <div class="mb-4">
            <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="baseRef" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="2" tab="操作记录" v-if="props.showType !== 'ADD'">
          <div class="mb-4">
            <DynamicTable :tables="dyTable" :config="dyTableConfig" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="文件目录" v-if="props.showType !== 'ADD'">
          <div class="mb-4">
            <a-row :gutter="20">
              <a-col :span="8">
                <!-- 档案详情 -->
                <div class="border border-gray-200 shadow-md rounded-md py-4 px-2 h-full max-height">
                  <DynamicForm v-show="dyDetailConfig.data" :config="dyDetailConfig" :questions="dyDetailQuestions" ref="detailRef" />
                  <a-empty class="!m-0 absolute left-1/2 transform -translate-x-1/2 top-1/2 -translate-y-1/2" v-show="!dyDetailConfig.data" :image="Empty.PRESENTED_IMAGE_SIMPLE" />
                </div>
              </a-col>
              <a-col :span="8">
                <!-- 预览目录 -->
                <div class="border border-gray-200 shadow-md rounded-md py-4 px-2">
                  <DynamicForm :config="dyTitleConfig" :questions="dyTitleQuestions" />
                  <DynamicTable :config="dyListConfig" :tables="dyListTables" @onSelectChange="appendBox" ref="listRef" />
                </div>
              </a-col>
              <a-col :span="8" v-if="props.showType !== 'VIEW'">
                <!-- 目标档案盒 -->
                <div class="border border-gray-200 shadow-md rounded-md py-4 px-2 max-height2">
                  <DynamicForm :config="dyTargetFileConfig" :questions="dyTargetFileQuestions" ref="targetFormRef" />
                  <DynamicTable :config="dyTargetFileConfig" :tables="dyTargetFileTables" @onSelectChange="deleteBox" ref="targetFileRef" />
                </div>
              </a-col>
            </a-row>
          </div>
        </a-tab-pane>
      </a-tabs>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" :disabled="data.status == 0 && showType == 'VIEW'" :loading="state.loading" @click="handleOk">{{ OK_TEXT[showType] }}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { DynamicForm } from '@/components/public-template';
import { DynamicTable } from '@/components/public-template';
import { boxAdd, boxUpdate } from '@/config/api/archives';
import { DYNAMICLTABLECLICKROW, INITSERVE, RESETTABLE } from '@/mixins/subject/subject-types';
import viewService from './viewDialog.service';
import { message } from 'ant-design-vue';
import previewService from './previewDialog.service';
import { Api } from '@/config/api/archives';
import { Empty } from 'ant-design-vue';
import { filter } from 'rxjs/operators';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object
  },
  // VIEW：查看 EDIT：编辑
  showType: {
    type: String,
    default: ''
  }
});

onMounted(() => {});
const emit = defineEmits(['update:visible', 'handleEdit']);
const state = reactive({
  loading: false,
  activeKey: '1',
  disabled: true
});
const TITLE = {
  ADD: '添加档案盒',
  VIEW: '档案盒详情',
  EDIT: '编辑档案盒'
};
const OK_TEXT = {
  ADD: '确定',
  VIEW: '编辑',
  EDIT: '确定'
};
const baseRef = ref(null);
const listRef = ref(null);
const detailRef = ref(null);
const targetFileRef = ref(null);
const targetFormRef = ref(null);
const dyConfig: any = {
  type: 'layer',
  grid: props.showType === 'ADD' ? 12 : 6,
  labelCol: 12,
  wrapperCol: 24,
  layout: 'vertical',
  cancelSave: true,
  data: props.data
};
const dyTitleConfig: any = {
  grid: 24,
  labelCol: { style: { width: 'auto' } },
  wrapperCol: 24,
  cancelSave: true
};
const dyTitleQuestions = reactive(previewService.getTitleQuestions());
const dyTargetFileConfig: any = reactive({
  cancelSave: true,
  grid: 24,
  labelCol: { style: { width: 'auto' } },
  wrapperCol: 24,
  name: 'TargetFileTable',
  rowKey: 'id',
  rowClick: true,
  notSelectChange: true,
  rowSelection: {
    type: 'checkbox'
  },
  noPagination: true
});
const dyTargetFileQuestions = reactive(previewService.getTargetFileQuestions(dyTargetFileConfig.data?.attachment?.toDepartment));
const dyListConfig: any = reactive({
  name: 'listTable',
  queryUrl: Api.boxPreviewCatalog,
  protType: 'post',
  noPagination: true,
  rowClick: true,
  notSelectChange: true,
  rowClickId: props.data.id,
  rowKey: 'id',
  rowSelection:
    props.showType === 'EDIT'
      ? {
          type: 'checkbox'
        }
      : null,
  params: {
    boxId: props.data.id
  },
  beforeWithMethod: (data) => {
    initData(data);
    return data;
  }
});
const dyDetailConfig: any = reactive({
  name: 'detailForm',
  labelCol: 24,
  wrapperCol: 24,
  grid: 12,
  layout: 'vertical',
  cancelSave: true,
  data: null
});
let dyDetailQuestions = reactive(previewService.getDetailQuestions(dyDetailConfig.data?.attachment?.archiveFileId));
const { proxy }: any = getCurrentInstance();
const subscribeSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === DYNAMICLTABLECLICKROW && item.value?.name === 'listTable') {
      dyDetailConfig.data = item.value.data;
      dyDetailQuestions[19].state.params.previewId = dyDetailConfig.data?.attachment?.archiveFileId;
      detailRef.value.getData();
    }
  });
const dyListTables: any = reactive(previewService.getListTables());
const dyTargetFileTables: any = reactive(previewService.getTargetFileTables());

function initData(list) {
  // 默认选择第一条
  if (Array.isArray(list) && list.length > 0) {
    list.forEach((item) => {
      item.boxCode = props.data.code;
      item.boxName = props.data.boxName;
      item.boxDesc = props.data.name;
    });
    listRef.value.selectedRowIndex = list[0].id;
    dyDetailConfig.data = list[0];
    dyDetailQuestions[19].state.params.previewId = dyDetailConfig.data?.attachment?.archiveFileId;
    detailRef.value.getData();
  }
}

const dyTableConfig: any = {
  data: props.data?.checkrecords,
  noPagination: props.data?.checkrecords?.length < 10
};
const dyQuestions: any = reactive(props.showType == 'VIEW' ? viewService.getViewQuestions() : viewService.getQuestions(props.data, props.showType));
const dyTable: any = reactive(viewService.getTables());
function handleOk() {
  if (props.showType == 'VIEW') {
    emit('handleEdit', props.data);
  } else {
    baseRef.value.onFinish((params) => {
      // state.loading = true;
      const fun = props.showType == 'ADD' ? boxAdd : boxUpdate;
      // 没点到第三个Tabs栏的情况
      if (!targetFormRef.value) {
        fun(params)
          .then((result) => {
            if (result.success) {
              message.success(`${props.showType == 'ADD' ? '添加' : '修改'}成功`);
              proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'boxDist' } });
              emit('update:visible', false);
            }
            state.loading = false;
          })
          .catch((err) => {
            state.loading = false;
            return Promise.reject(err);
          });
      } else {
        // 点到第三个Tabs栏的情况
        targetFormRef.value &&
          targetFormRef.value.onFinish((data) => {
            if (targetFileRef.value.dataList.value.length > 0 && !data.filesBoxId) {
              return message.warn('请选择目标档案盒');
            }
            params.targetBoxId = data.filesBoxId;
            params.arcList = targetFileRef.value.dataList.value.map((item) => item.id);
            fun(params)
              .then((result) => {
                if (result.success) {
                  message.success(`${props.showType == 'ADD' ? '添加' : '修改'}成功`);
                  proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'boxDist' } });
                  emit('update:visible', false);
                }
                state.loading = false;
              })
              .catch((err) => {
                state.loading = false;
                return Promise.reject(err);
              });
          });
      }
    });
  }
}

// 左侧移入右侧
function appendBox(oldSelectedRows) {
  if (props.showType === 'VIEW') return;
  // 选中文件带出归档部门, 档案盒类型一致的可选项
  for (let i = 0; i < dyTargetFileQuestions.length; i++) {
    if (dyTargetFileQuestions[i].key == 'filesBoxId') {
      dyTargetFileQuestions[i].value = null;
      dyTargetFileQuestions[i].state.params.typeId = oldSelectedRows[0].filesType;
      dyTargetFileQuestions[i].state.params.toDepartment = oldSelectedRows[0].toDepartment;
      dyTargetFileQuestions[i].state.params.filesBoxId = oldSelectedRows[0].filesBoxId;
    }
  }
  proxy.$NotificationFormSub.pushParams({
    key: INITSERVE,
    value: {
      initKeys: 'filesBoxId',
      configName: 'TargetFileTable'
    }
  });
  listRef.value.dataList.value = listRef.value.dataList.value.filter((item1) => !oldSelectedRows.some((item2) => item2.id === item1.id));
  targetFileRef.value.dataList.value.push(...oldSelectedRows);
  targetFileRef.value.selectedRows = targetFileRef.value.dataList.value;
  targetFileRef.value.selectedRowKeys.value = targetFileRef.value.dataList.value.map((item) => item.id);
  targetFileRef.value.selectedValue.value = targetFileRef.value.dataList.value.map((item) => item.id);
  console.log('oldSelectedRows', oldSelectedRows);
}
// 右侧移入左侧
function deleteBox(oldSelectedRows) {
  if (!oldSelectedRows.length) {
    listRef.value.selectedRows = [];
    listRef.value.selectedRowKeys.value = [];
    listRef.value.selectedValue.value = [];
    listRef.value.dataList.value.push(...targetFileRef.value.dataList.value);
    targetFileRef.value.dataList.value = [];
  } else {
    listRef.value.selectedRows = [];
    listRef.value.selectedRowKeys.value = [];
    listRef.value.selectedValue.value = [];
    listRef.value.dataList.value.push(targetFileRef.value.dataList.value.find((item2) => !oldSelectedRows.some((item1) => item1.id === item2.id)));
    targetFileRef.value.dataList.value = oldSelectedRows;
  }
  // 选中文件带出归档部门, 档案盒类型一致的可选项
  for (let i = 0; i < dyTargetFileQuestions.length; i++) {
    if (dyTargetFileQuestions[i].key == 'filesBoxId') {
      dyTargetFileQuestions[i].value = null;
      dyTargetFileQuestions[i].state.params.typeId = targetFileRef.value.dataList.value[0]?.filesType;
      dyTargetFileQuestions[i].state.params.toDepartment = targetFileRef.value.dataList.value[0]?.toDepartment;
      dyTargetFileQuestions[i].state.params.filesBoxId = oldSelectedRows[0].filesBoxId;
    }
  }
  proxy.$NotificationFormSub.pushParams({
    key: INITSERVE,
    value: {
      initKeys: 'filesBoxId',
      configName: 'TargetFileTable'
    }
  });
  targetFileRef.value.selectedRows = targetFileRef.value.dataList.value;
  targetFileRef.value.selectedRowKeys.value = targetFileRef.value.dataList.value.map((item) => item.id);
  targetFileRef.value.selectedValue.value = targetFileRef.value.dataList.value.map((item) => item.id);
  console.log('oldSelectedRows', oldSelectedRows);
}
function handleCancel() {
  emit('update:visible', false);
}
onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.ant-form) {
  .ant-col:last-child {
    .ant-form-item {
      margin-bottom: 0;
    }
  }
}
.modal {
  :deep(.editBox) {
    width: 1352px !important;
    .ant-modal-body {
      padding-top: 0;
    }
  }
  :deep(.addBox) {
    width: 760px !important;
  }
  :deep(.ant-tabs-content-holder) {
    .ant-table-body {
      height: 402px;
      .ant-table-placeholder {
        height: 358px;
        .ant-table-cell {
          border-bottom: none;
        }
      }
    }
    .max-height {
      height: 527px;
      overflow-y: scroll;
    }
    .max-height2 {
      .ant-table-body {
        height: 358px;
      }
    }
  }
}
:deep(.ant-modal-footer) {
  text-align: center;
}
:deep(.ant-modal-content) {
  border-radius: 6px;
  .ant-modal-header {
    border-radius: 6px 6px 0 0;
  }
}
/deep/ .ant-form-horizontal > .ant-row > .ant-col-24 {
  margin-bottom: 12px;
  padding: 0 !important;
}
.modal {
  .transfer {
    height: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
</style>
